package peng.filter;



import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 静态文件 img file
 * Created by hao on 2017/11/24.
 */
public class ThemesResourceFilter implements Filter {





    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {


        /*HttpServletRequest request = (HttpServletRequest)req;
        ServletContext servletContext = request.getSession().getServletContext();// app端并不保持长连接，因此此处获取session不能用 getSession(false) ，他会返回空的session
        String uri = URLDecoder.decode(request.getRequestURI(), "utf-8");
        uri = uri.replace(request.getContextPath(), "");//移除项目名称

        setHeaders((HttpServletResponse) resp, getMediaType(servletContext, uri));
        String imgPath = "";//SystemParamConfig.getImgFilePath();
        String file = "";
        if(uri.startsWith("/appimg")){//appimg
            if(StringUtils.isEmpty(imgPath)){
                chain.doFilter(req, resp);
                return;
            }else{
                // logger.info("请求静态资源路径："+uri);
                file  = imgPath + uri.replaceAll("/appimg","");
            }
        }else if(uri.startsWith("/upload")){//upload
            if(org.apache.commons.lang.StringUtils.isEmpty(imgPath) ){
                chain.doFilter(req, resp);
                return;
            }else{
                file  = imgPath + URLDecoder.decode(request.getRequestURI(), "utf-8");
            }
        }else if(uri.startsWith("/dataUploadImg")){//upload
            String taskAttachmentFilePath = SystemParamConfig.getDataUploadImgPath();
            if(StringUtils.isEmpty(taskAttachmentFilePath) ){
                chain.doFilter(req, resp);
                return;
            }else{
                file  = taskAttachmentFilePath + uri.replaceAll("/" + AppStatic.APP_DATA_UPLOAD_IMG, "");
            }
        }else if(uri.startsWith("/"+AppStatic.QRCODE)){//upload
            String taskAttachmentFilePath = SystemParamConfig.getQrcodeCreatePath();
            if(StringUtils.isEmpty(taskAttachmentFilePath) ){
                chain.doFilter(req, resp);

                return;
            }else{
                file  = taskAttachmentFilePath + uri.replaceAll("/" + AppStatic.QRCODE, "");
            }
        }

        File fileInfo = new File(file);
        if(!fileInfo.exists()){
            return;
        }

        InputStream inputStream = new FileInputStream(fileInfo);

        StreamUtils.copy(inputStream, resp.getOutputStream());
        return;*/

    }



    @Override
    public void init(FilterConfig config) throws ServletException {
    }


    @Override
    public void destroy() {
    }


    protected void setHeaders(HttpServletResponse response, MediaType mediaType) throws IOException {

        if(mediaType != null) {
            response.setContentType(mediaType.toString());
        }
    }





    private static class ActivationMediaTypeFactory {
        private static final FileTypeMap fileTypeMap = loadFileTypeMapFromContextSupportModule();

        private ActivationMediaTypeFactory() {
        }

        private static FileTypeMap loadFileTypeMapFromContextSupportModule() {
            ClassPathResource mappingLocation = new ClassPathResource("org/springframework/mail/javamail/mime.types");
            if(mappingLocation.exists()) {
                InputStream inputStream = null;

                MimetypesFileTypeMap ex;
                try {
                    inputStream = mappingLocation.getInputStream();
                    ex = new MimetypesFileTypeMap(inputStream);
                } catch (IOException var12) {
                    return FileTypeMap.getDefaultFileTypeMap();
                } finally {
                    if(inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException var11) {
                            ;
                        }
                    }

                }

                return ex;
            } else {
                return FileTypeMap.getDefaultFileTypeMap();
            }
        }

        public static MediaType getMediaType(String filename) {
            String mediaType = fileTypeMap.getContentType(filename);
            return StringUtils.hasText(mediaType)?MediaType.parseMediaType(mediaType):null;
        }
    }



    protected MediaType getMediaType(ServletContext servletContext, String uri) {
        MediaType mediaType = null;
        String mimeType = servletContext.getMimeType(uri);
        if(StringUtils.hasText(mimeType)) {
            mediaType = MediaType.parseMediaType(mimeType);
        }
        return mediaType;
    }
}
